//
//  YYEComposeViewController.swift
//  weibo14
//
//  Created by mac on 16/3/11.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class YYEComposeViewController: UIViewController {

    // toolBar是否要执行跟随键盘的动画
    lazy var isToolBarAnimation: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    private func setupUI(){
    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "back")
        
        navigationItem.titleView = titleView
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        //-----------中间部分
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        
        // 那个图片框
        textView.addSubview(PictureView)
        
        PictureView.selectedPictureClosure = {
            self.selectPicture()
        }
        
        PictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(100)
            make.leading.equalTo(10)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
        }

        
        // -----------toolber部分
        view.addSubview(toolbar)
        
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.leading.trailing.equalTo(self.view)
            make.height.height.equalTo(35)
        }
        
        
        toolbar.btnClickCallBack = { (btn:UIButton)->() in
            
            switch btn.tag {
            case YYEComposeToolbarButtonType.Picture.rawValue:
                print("图片")
                self.selectPicture()
            case YYEComposeToolbarButtonType.Mention.rawValue:
                print("Mention")
            case YYEComposeToolbarButtonType.Emoticon.rawValue:
                print("表情")
                self.switchKeyboard()
            case YYEComposeToolbarButtonType.Trend.rawValue:
                print("话题")
            case YYEComposeToolbarButtonType.Add.rawValue:
                print("加号")
            default:
                print("其他")
            }
        }
        
        // 监听键盘弹出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 监听表情按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonClick:", name: YYEEmoticonDidSelectedNotification, object: nil)

        // 监听删除按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDelDidSelected", name: YYEKeyboardDelDidSelectedNotification, object: nil)

        
        
    }
    // 切换键盘
    /// 切换键盘
    private func switchKeyboard(){
        
        // 如果当前是系统键盘,就切换成表情键盘
        if textView.inputView == nil {
            // 设置textView.inputView
            textView.inputView = emoticonKeyboard
            
            toolbar.isSystemKeyboard = false
        }else{
            // 当前是表情键盘,就切换成系统键盘
            textView.inputView = nil
            toolbar.isSystemKeyboard = true
        }

        isToolBarAnimation = false
        // 取消第一响应者,会发送键盘frame改变的通知,由于我们监听过此通知,所以composetoolBar会执行一个0.25秒的往下的动画,而在0.25秒的动画还没有执行完毕的时候,我们又成为了第一响应者,这个时候又发送了一个键盘frame改变的通知,所以就造成抖动,解决方法就是,第一次取消第一响应的时候不需要去执行动画.
        textView.resignFirstResponder()
        
        
        isToolBarAnimation = true        // 成为第一响应者
        textView.becomeFirstResponder()
        
    }

    
    // 一个方法,图片选择器  开区图片选择器
    private func selectPicture() {
        let vc = UIImagePickerController()
        // 设置成为代理,为了取得点击之后的图片
        vc.delegate = self
        // 1. 判断照相机是否可用
        //        if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front) {
        //            // 指定数据来源的类型
        //            vc.sourceType = .Camera
        //        }
        
        // UIImagePickerController.isSourceTypeAvailable(.Camera)
        // 设置是否可以编译
        vc.allowsEditing = true
        
    
        
        self.presentViewController(vc, animated: true, completion: nil)
    }
    
    // 键盘的东环
    @objc private func keyboardWillChangeFrame(info:NSNotification) {
    
        
        if isToolBarAnimation == false {
            return
        }
        //[UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 736}, {414, 271}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {207, 600.5}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {414, 271}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 465}, {414, 271}}, UIKeyboardAnimationDurationUserInfoKey: 0.25, UIKeyboardCenterBeginUserInfoKey: NSPoint: {207, 871.5}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1]
        
        // print(info.userInfo)
        let dict = info.userInfo
        let duration = (dict![UIKeyboardAnimationDurationUserInfoKey]! as! NSNumber).doubleValue
        let endFrame = (dict![UIKeyboardFrameEndUserInfoKey]! as! NSValue).CGRectValue()
        
        self.toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(endFrame.origin.y-SCREENH)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            self.toolbar.layoutIfNeeded()
        }

    }
    
    
    
    /// 表情按钮点击的通过触发的方法
    @objc private func emoticonButtonClick(noti: NSNotification) {
        
        
        // 取到表情模型
        let emoticon = noti.userInfo!["emoticon"]! as! YYEEmoticon
        
        textView.insertEmoticon(emoticon)
        
    }

    @objc private func back(){
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    @objc private func sendMessage(){

        if PictureView.images.count > 0 {
            // 发表图片微博
            upload()
        }else{
            // 发表文字微博
            update()
        }
    }
    
    
    @objc private func keyboardDelDidSelected(){
        // 删除按钮点击要执行的逻辑
        textView.deleteBackward()
    }

    // 发送文字的微博
    private func update(){
                YYENetworkTools.sharedTools.upData(textView.emoticonText) { (responseObject, error) -> () in
        
                    if error != nil {
                        print("发表失败\(error)")
                        SVProgressHUD.showErrorWithStatus("发表失败")
                        return
                    }
                    SVProgressHUD.showSuccessWithStatus("发表成功")
                }
    }
    // 发送图片微博
    private func upload(){
    

        YYENetworkTools.sharedTools.upload(textView.emoticonText, image:  PictureView.images.first!) { (responseObject, error) -> () in
    
                if error != nil {
                    print("发表失败\(error)")
                    SVProgressHUD.showErrorWithStatus("图片发表失败")
                    return
                }

            SVProgressHUD.showSuccessWithStatus("图片发表成功")
        }
    }
    
    
    /// ------------代理方法--------
    func scrollViewDidScroll(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }

    deinit {
      NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 懒加载控件 ----非常特殊的一个控件
    private lazy var  titleView:UILabel = {
    
        let lable = UILabel()
        
        if let name = YYEUserAccountViewModel.sharedAccountViewModel.account?.screen_name {
 
            let lableText = "发微博\n\(name)"
            // 初始化一个带有属性的文字 ----的字符传
            let attrText = NSMutableAttributedString(string: lableText)
            //  attrText.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, 3))
            // 定义需要设置的属性
            let attrDict = [
                NSForegroundColorAttributeName: UIColor.lightGrayColor(),
                NSFontAttributeName: UIFont.systemFontOfSize(14),
                //  NSStrokeWidthAttributeName: 2, // 线宽
                //  NSStrokeColorAttributeName: UIColor.redColor() // 线的颜色
            ]
            // 求出昵称所在的范围
            let range = (lableText as NSString).rangeOfString(name)
            // 添加属性
            attrText.addAttributes(attrDict, range: range)

            // 这个也要注意
            lable.attributedText = attrText
        
        } else {
        
            lable.text = "发微博"
        }
        
        lable.numberOfLines = 2
        
        lable.textAlignment = .Center
        
        lable.sizeToFit()
        
        return lable
    }()
    // 右边的按钮
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        
        button.addTarget(self, action: "sendMessage", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        // 设置不同状态下文字颜色
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        // 设置文字
        button.setTitle("发送", forState: UIControlState.Normal)
        // 设置字体大小
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        // 设置按钮的大小
        button.frame.size = CGSize(width: 40, height: 34)
        // 设置不可用
        //        button.enabled = false
        return button
    }()
    // 输入框
    private lazy var textView: YYETextView = {
        let textView = YYETextView(frame: CGRectZero, textContainer: nil)
        textView.delegate = self
        textView.placeholder = "听说下雨天音乐和辣雨天音乐和辣雨天音乐和辣雨天音乐和辣雨天音乐和辣雨天音乐和辣雨天音乐和辣条更配哟~~听说下雨天音乐和辣条更配哟~~听说下雨天音乐和辣条更配哟~~"
        textView.font = UIFont.systemFontOfSize(15)
        return textView
    }()
    // toolbar
    private lazy var toolbar:YYEComposeToolbar = {
        let bar = YYEComposeToolbar(frame: CGRectZero)
        return bar
    }()
    // 图片选择view
    private lazy var PictureView:YYEComposePictureView = {
    
        let view = YYEComposePictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        return view
    }()
    // 懒加载控件  自定义的键盘 替换原来的键盘
    private lazy var emoticonKeyboard: YYEEmoticonKeyboard = {
        let keyboard = YYEEmoticonKeyboard()
        keyboard.frame = CGRect(origin: CGPointZero, size: CGSize(width: SCREENW, height: 216))
        return keyboard
    }()
    
}
extension YYEComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }

}

extension YYEComposeViewController:UIImagePickerControllerDelegate ,UINavigationControllerDelegate{

    // 这个方法哪里来的
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
       
 
        let scaleImage = image.scaleToWidth(100)
        
        PictureView.addImage(scaleImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
     
        picker.dismissViewControllerAnimated(true, completion: nil)
    
    }
}

